package com.snimay.javacompiler.compiler;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.tools.DiagnosticCollector;
import javax.tools.JavaCompiler;
import javax.tools.JavaFileObject;
import javax.tools.ToolProvider;

 

/**   
 * @Title      : JavaFile.java
 * @Package    : com.snimay.javacompiler.compiler
 * @Description: 新建java 的*.class 
 * @author     : xxy
 * @date       : 2018年5月28日 下午4:53:32
 * @version    : V1.0   
 */
public class JavaFile {
	/**
	 * @Description: TODO
	 * @author     : 设置代码
	 * @param code
	 * @return
	 * @throws
	 */
	public Boolean setFile(String code) {
		JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
        DiagnosticCollector<JavaFileObject> collector = new DiagnosticCollector<>();
        List<String> options = new ArrayList<>();
        options.addAll(Arrays.asList("-d",JavaFile.class.getClassLoader().getResource("").getPath()));  
       // System.out.println(App.class.getClassLoader().getResource("").getPath());
        Pattern CLASS_PATTERN = Pattern.compile("class\\s+([$_a-zA-Z][$_a-zA-Z0-9]*)\\s*");
        Matcher matcher = CLASS_PATTERN.matcher(code);
        String cls;
        if(matcher.find()){
            cls = matcher.group(1);
        } else{
            throw new IllegalArgumentException("No such class name in " + code);
        }
        JavaFileObject javaFileObject = new MyJavaFileObject(cls, code);
        Boolean result = compiler.getTask(null, null, collector, options, null, Arrays.asList(javaFileObject)).call();
        return result;
	}
}
